package pld.car.service.impl;

import pld.car.service.*;

public class PageServiceImpl implements PageService {
	private int startPageNumber;// 页数工具栏起始页码

	private int endPageNumber;// 页数工具栏终止页码

	private int pageNumber;// 当前页码

	private int totalElements;// 总记录数

	private int pageCount;// 总页数

	private int firstItemThisPage;// 展示页的第一条记录号

	public PageServiceImpl() {
		System.out.println("PageServiceImpl init!");
	}

	public void initParams(int count, int pageNo, int rowCountPerPage, int maxPageInBar) {
		this.totalElements = count;
		this.pageCount = this.getPageCount(rowCountPerPage);
		if (pageNo % maxPageInBar == 0) {
			this.startPageNumber = pageNo - maxPageInBar + 1;
		} else {
			this.startPageNumber = (pageNo / maxPageInBar) * maxPageInBar + 1;
		}
		int temp = this.startPageNumber + maxPageInBar - 1;
		this.endPageNumber = (temp > this.pageCount) ? this.pageCount : temp;
		this.pageNumber = pageNo;
		this.firstItemThisPage = (this.pageNumber - 1) * rowCountPerPage;
	}

	public String createPageBar(){
		//condition = java.net.URLEncoder.encode(condition,"UTF-8");
		StringBuffer sb = new StringBuffer();
		sb.append("<table><tbody><tr>");
		sb.append("<td>共").append(this.totalElements).append("条记录&nbsp;&nbsp;&nbsp;&nbsp;</td>");
		for (int i = this.startPageNumber; i <= this.endPageNumber; i++) {
			if (i == this.pageNumber) {
				sb.append("<td>&nbsp;&nbsp;").append(i).append("&nbsp;&nbsp;</td>");
			} else {
				sb.append("<td>&nbsp;&nbsp;<a href=\"javascript:loadNews(").append(i).append(")\">").append(i).append("</a>&nbsp;&nbsp;</td>");
			}
		}
		sb.append("<td>&nbsp;&nbsp;共<span id='pageCount' value='").append(this.pageCount).append("'>").append(this.pageCount).append("</span>页&nbsp;&nbsp;</td>");
		sb.append("<td>到第&nbsp;&nbsp;<input type='text' id='pageNoInput' size='6' maxlength='6'/>&nbsp;&nbsp;页&nbsp;&nbsp;").append("<input type='button' value='确 定' onclick='changeRandomPage()'/></td>");
		sb.append("</tr><tbody></table>");
		System.out.print(sb.toString());
		return sb.toString();
	}

	public int getPageCount(int rowCountPerPage) {
		double total = this.totalElements;
		return (int) (Math.ceil(total / rowCountPerPage));
	}

	public int getFirstItemThisPage() {
		return firstItemThisPage;
	}

	public void setFirstItemThisPage(int firstItemThisPage) {
		this.firstItemThisPage = firstItemThisPage;
	}

}
